﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MDIDemo.Windows;
using DevExpress.XtraEditors;
using System.Net;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;

namespace MDIDemo.Modules
{
    public partial class NXHoaDon : DevExpress.XtraEditors.XtraForm
    {
        string sErr = "";
        long no = -1;
        string sobt = "";
        double giavon = 0;
        static string url = "http://gdt.gov.vn/wps/portal/!ut/p/b1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOINTCw9fSzCgv2dzLxdDTxDHV2NLAM8jC3CzPQLsh0VAVXv_MU!/?mst={0}&action=myform";
        //http://gdt.gov.vn/wps/portal/!ut/p/b1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOINTCw9fSzCgv2dzLxdDTxDHV2NLAM8jC3CzPQLsh0VAVXv_MU!/?mst=0100231603-006&action=action&id=0100231603-006
        //1100549268
        int idDieuChinh = 61;
        int idInHoaDon = 62;
        int idThem = 49;
        int idSua = 50;
        int idXoa = 51;
        void SetPermission()
        {
            if (this.Parent.Parent is frmMain)
            {
                frmMain main = (frmMain)this.Parent.Parent;
                btnThem.Visible = frmMain.IsPermis(idThem, main.CurrentPermis.PERMISSION);
                btnSua.Visible = frmMain.IsPermis(idSua, main.CurrentPermis.PERMISSION);
                btnXoa.Visible = frmMain.IsPermis(idXoa, main.CurrentPermis.PERMISSION);
                btnLuu.Visible = frmMain.IsPermis(idThem, main.CurrentPermis.PERMISSION) || frmMain.IsPermis(idSua, main.CurrentPermis.PERMISSION);
            }
        }
        bool isInHD = false;
        public NXHoaDon()
        {
            InitializeComponent();

        }

        private void btnTimKhachHang_Click(object sender, EventArgs e)
        {
            frmViewKhachHang frm = new frmViewKhachHang();
            frm.IsSupplier = rType.EditValue.ToString() == "Supplier";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                txtMaKhachHang.Text = frm.ReturnRow[DTO.CUSTINFOInfo.Field.CUSTID.ToString()].ToString();
                txtTenKhachHang.Text = frm.ReturnRow[DTO.CUSTINFOInfo.Field.TENGD.ToString()].ToString();
                //txtDiaChi.Text = frm.ReturnRow[DTO.CUSTINFOInfo.Field.DIACHI.ToString()].ToString();
                txtNgayPS.Focus();
            }
        }

        private void NXHoaDon_Load(object sender, EventArgs e)
        {
            gbDetail.AppearanceCaption.ForeColor = Color.Blue;
            gbDetail.Text = gbDetail.Text.ToUpper();
            EnabledForm(false);
            RefresForm("");
            LoadTonHang();
            SetPermission();
        }

        private void LoadTonHang()
        {
            BUS.TONHANGControl ctr = new BUS.TONHANGControl();
            DataTable dt = ctr.GetAll(!ckbZero.Checked, ref sErr);
            gridTonHang.DataSource = dt;
            double total = 0;
            try { total = Convert.ToDouble(dt.Compute("SUM(" + DTO.TONHANGInfo.Field.SOTIEN.ToString() + ")", "")); }
            catch { }
            groupControl1.Text = "Tổng giá trị hàng hóa tồn kho: " + total.ToString("N0");
        }

        private void ckbZero_CheckedChanged(object sender, EventArgs e)
        {
            LoadTonHang();
        }

        private void btnNo_Click(object sender, EventArgs e)
        {
            frmViewTaiKhoan frm = new frmViewTaiKhoan();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                txtTK1.Text = frm.ReturnRow[DTO.ACC_SYSInfo.Field.TKC2.ToString()].ToString();
            }
        }

        private void btnCo1_Click(object sender, EventArgs e)
        {
            frmViewTaiKhoan frm = new frmViewTaiKhoan();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                txtTK2.Text = frm.ReturnRow[DTO.ACC_SYSInfo.Field.TKC2.ToString()].ToString();
            }
        }

        private void btnCo2_Click(object sender, EventArgs e)
        {
            frmViewTaiKhoan frm = new frmViewTaiKhoan();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                txtTK3.Text = frm.ReturnRow[DTO.ACC_SYSInfo.Field.TKC2.ToString()].ToString();
            }
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            RefresForm("");
            EnabledForm(true);
            btnTimKhachHang.Focus();
        }

        private void RefresForm(string p)
        {

            no = -1;
            sobt = "";
            txtTKValue2.EditValue = null;
            txtTKValue3.EditValue = null;
            txtDiaChi.Text = p;
            txtDoanhSo.EditValue = null;
            txtDonGia.EditValue = null;
            txtKyHieuHD.Text = p;
            txtMaKhachHang.Text = p;
            txtMaSoThue.Text = p;
            txtNgayPS.EditValue = frmMain.__ngayMoSo;
            txtNguoiMua.Text = p;
            txtTKValue1.EditValue = null;
            txtSoHD.Text = p;
            txtSoLuong.EditValue = null;
            txtTenDV.Text = p;
            txtTenKhachHang.Text = p;
            txtThanhTien.Text = p;
            txtThueGTGT.EditValue = null;
            txtThueSuat.EditValue = 10;
            ckbCaNhan.Checked = false;
            isInHD = false;
            giavon = 0;
            if (rType.EditValue.ToString() == "X-GTGT")
            {
                lbTK1.Text = "TK Nợ";
                lbTK2.Text = lbTK3.Text = "TK Có";
                txtTK1.Text = "1111";
                txtTK2.Text = "5111";
                txtTK3.Text = "33311";

            }
            else
            {
                lbTK1.Text = lbTK2.Text = "TK Nợ";
                lbTK3.Text = "TK Có";
                txtTK1.Text = "1561";
                txtTK2.Text = "1331";
                txtTK3.Text = "1111";
            }
            gridNXHoaDon.DataSource = DTO.NXHOADONInfo.ToDataTable();
        }

        private void EnabledForm(bool p)
        {
            bool isDieuChinh = true;
            if (this.Parent.Parent is frmMain)
            {
                frmMain main = this.Parent.Parent as frmMain;
                isDieuChinh = frmMain.IsPermis(idDieuChinh, main.CurrentPermis.PERMISSION);
            }
            if (frmMain.__khoaSo)
            {
                btnSua.Enabled = btnXoa.Enabled = btnThem.Enabled = btnXoa.Enabled = false;
            }
            else
            {
                colSOLUONG.OptionsColumn.ReadOnly = isDieuChinh & p;
                colGIABAN.OptionsColumn.ReadOnly = isDieuChinh & p;
                colGIAVON.OptionsColumn.ReadOnly = isDieuChinh & p;
                colSOLUONG.OptionsColumn.AllowEdit = !colSOLUONG.OptionsColumn.ReadOnly;
                colGIABAN.OptionsColumn.AllowEdit = !colGIABAN.OptionsColumn.ReadOnly;
                colGIAVON.OptionsColumn.AllowEdit = !colGIAVON.OptionsColumn.ReadOnly;

                btnSua.Enabled = btnXoa.Enabled = btnThem.Enabled = btnXoa.Enabled = !p;
            }


            //txtTKValue2.Properties.ReadOnly = !p;
            //txtTKValue3.Properties.ReadOnly = !p;
            btnTimKhachHang.Enabled = p;
            txtDiaChi.Properties.ReadOnly = !p;
            //txtDoanhSo.Properties.ReadOnly = !p;
            txtDonGia.Properties.ReadOnly = !p;
            txtKyHieuHD.Properties.ReadOnly = !p;
            //txtMaKhachHang.Properties.ReadOnly = !p;
            txtMaSoThue.Properties.ReadOnly = !p;
            txtNgayPS.Properties.ReadOnly = !p;
            txtNguoiMua.Properties.ReadOnly = !p;
            //txtTKValue1.Properties.ReadOnly = !p;
            txtSoHD.Properties.ReadOnly = !p;
            txtSoLuong.Properties.ReadOnly = !p;
            //txtTenDV.Properties.ReadOnly = !p;
            //txtTenKhachHang.Properties.ReadOnly = !p;
            //txtThanhTien.Properties.ReadOnly = !p;
            //txtThueGTGT.Properties.ReadOnly = !p;
            txtThueSuat.Properties.ReadOnly = !p;
            //txtTK2.Properties.ReadOnly = !p;
            //txtTK3.Properties.ReadOnly = !p;
            //txtTK1.Properties.ReadOnly = !p;
            ckbCaNhan.Enabled = p;
            btnThemChiTiet.Enabled = p;
            btnXoaChiTiet.Enabled = p;
            btnTK1.Enabled = p;
            btnTK2.Enabled = p;
            btnTK3.Enabled = p;

            btnLuu.Enabled = p;
            btnBoQua.Enabled = p;
            btnTimKiem.Enabled = !p;
            btnInCT.Enabled = !p;
            btnInHD.Enabled = !p;
            rType.Enabled = !p;
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            EnabledForm(true);
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            sErr = "";
            DataTable dt = gridNXHoaDon.DataSource as DataTable;
            if (dt == null || dt.Rows.Count == 0)
            {
                XtraMessageBox.Show("Vui lòng chọn mặt hàng để làm báo cáo!");
                return;
            }

            BUS.BAOCAOTHUEControl cbCtr = new BUS.BAOCAOTHUEControl();
            DTO.BAOCAOTHUEInfo bcInf = GetData();
            if (bcInf.ID == -1)
            {
                bcInf.SOBT = GetNewSoBT();
                no = bcInf.ID = cbCtr.Add(bcInf, ref sErr);
            }
            else sErr = cbCtr.Update(bcInf);
            if (sErr == "")
            {
                BUS.NXHOADONControl nxCtr = new BUS.NXHOADONControl();
                BUS.TONHANGControl tonHCtr = new BUS.TONHANGControl();
                //sErr = nxCtr.Delete(bcInf.ID);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i].RowState != DataRowState.Deleted)
                    {

                        DTO.NXHOADONInfo detailInf = new DTO.NXHOADONInfo(dt.Rows[i]);
                        detailInf.NO = bcInf.ID;
                        detailInf.SOBT = bcInf.SOBT;
                        detailInf.LINE = i;
                        //DTO.TONHANGInfo toninf = tonHCtr.Get(detailInf.MAHANG, ref sErr);
                        DTO.TONHANGInfo tonHangInf = tonHCtr.Get(detailInf.MAHANG, ref sErr);
                        if (rType.EditValue.ToString() == "X-GTGT")
                        {
                            tonHangInf.SOLUONG -= detailInf.SOLUONG;
                            tonHangInf.SOTIEN -= detailInf.TIENVON;
                        }
                        else
                        {
                            tonHangInf.SOLUONG += detailInf.SOLUONG;
                            tonHangInf.SOTIEN += detailInf.SOTIEN;
                            tonHangInf.GIAVON = tonHangInf.SOTIEN / tonHangInf.SOLUONG;
                        }
                        tonHCtr.Update(tonHangInf);
                        nxCtr.Add(detailInf, ref sErr);
                    }
                    else
                    {
                        DataView myView = new DataView(dt, null, null, DataViewRowState.Deleted);
                        DataTable dtDeleted = myView.ToTable();
                        foreach (DataRow row in dtDeleted.Rows)
                        {
                            DTO.NXHOADONInfo detailInf = new DTO.NXHOADONInfo(dt.Rows[i]);
                            DTO.TONHANGInfo tonHangInf = tonHCtr.Get(detailInf.MAHANG, ref sErr);
                            if (rType.EditValue.ToString() == "X-GTGT")
                            {
                                tonHangInf.SOLUONG += detailInf.SOLUONG;
                                tonHangInf.SOTIEN += detailInf.TIENVON;
                            }
                            else
                            {
                                tonHangInf.SOLUONG -= detailInf.SOLUONG;
                                tonHangInf.SOTIEN -= detailInf.TIENVON;
                            }
                            tonHCtr.Update(tonHangInf);
                            nxCtr.Delete(detailInf.NO, detailInf.LINE);
                        }
                    }


                }
                LoadTonHang();
                BUS.HACHTOANControl htCtr = new BUS.HACHTOANControl();
                htCtr.Delete(bcInf.ID, ref sErr);
                if (rType.EditValue.ToString() == "X-GTGT")
                {
                    DTO.HACHTOANInfo htInf1 = new DTO.HACHTOANInfo(bcInf.ID, 1, bcInf.SOBT, rType.EditValue.ToString(), frmMain.__ngayMoSo, txtTK1.Text, txtTK2.Text, Convert.ToDouble(txtTKValue2.EditValue), "");
                    DTO.HACHTOANInfo htInf2 = new DTO.HACHTOANInfo(bcInf.ID, 2, bcInf.SOBT, rType.EditValue.ToString(), frmMain.__ngayMoSo, txtTK1.Text, txtTK3.Text, Convert.ToDouble(txtTKValue3.EditValue), "");
                    DTO.HACHTOANInfo htInf3 = new DTO.HACHTOANInfo(bcInf.ID, 3, bcInf.SOBT, rType.EditValue.ToString(), frmMain.__ngayMoSo, "632", "1561", giavon, "");
                    htCtr.Add(htInf1, ref sErr);
                    htCtr.Add(htInf2, ref sErr);
                    htCtr.Add(htInf2, ref sErr);
                }
                else
                {
                    DTO.HACHTOANInfo htInf1 = new DTO.HACHTOANInfo(bcInf.ID, 1, bcInf.SOBT, rType.EditValue.ToString(), frmMain.__ngayMoSo, txtTK1.Text, txtTK3.Text, Convert.ToDouble(txtTKValue1.EditValue), "");
                    DTO.HACHTOANInfo htInf2 = new DTO.HACHTOANInfo(bcInf.ID, 2, bcInf.SOBT, rType.EditValue.ToString(), frmMain.__ngayMoSo, txtTK2.Text, txtTK3.Text, Convert.ToDouble(txtTKValue2.EditValue), "");
                    htCtr.Add(htInf1, ref sErr);
                    htCtr.Add(htInf2, ref sErr);
                }
                if (txtMaSoThue.Text != "")
                {
                    BUS.CommonControl ctr = new BUS.CommonControl();
                    ctr.executeNonQuery(String.Format("UPdate MASOTHUE set TENCOQUAN =N'{1}' WHERE MST='{0}'", txtMaSoThue.Text, txtDiaChi.Text));
                }
                EnabledForm(false);
            }
            else XtraMessageBox.Show(sErr);
        }

        private DTO.BAOCAOTHUEInfo GetData()
        {
            DateTime ngayPS = txtNgayPS.EditValue != null ? Convert.ToDateTime(txtNgayPS.EditValue) : frmMain.__ngayMoSo;
            double doanhSo = txtDoanhSo.EditValue != null ? Convert.ToDouble(txtDoanhSo.EditValue) : 0;
            short thuesuat = txtThueSuat.EditValue != null ? Convert.ToInt16(txtThueSuat.EditValue) : Convert.ToInt16(0);
            double thueGTGT = txtThueGTGT.EditValue != null ? Convert.ToDouble(txtThueGTGT.EditValue) : 0;
            DTO.BAOCAOTHUEInfo inf = new DTO.BAOCAOTHUEInfo(no, ngayPS, txtKyHieuHD.Text, txtSoHD.Text, txtTenDV.Text, txtMaSoThue.Text, txtNguoiMua.Text, doanhSo, thuesuat, thueGTGT, "", rType.EditValue.ToString() == "X-GTGT", txtDiaChi.Text, sobt, isInHD, frmMain.__ngayMoSo, txtMaKhachHang.Text, rType.EditValue.ToString(), frmMain.__userID, frmMain.__userID, DateTime.Now, DateTime.Now);
            inf.GHICHU = ckbCaNhan.Checked ? "Cá nhân" : "Doanh nghiệp";
            return inf;
        }

        public static string GetNewSoBT()
        {
            BUS.BAOCAOTHUEControl bcCtr = new BUS.BAOCAOTHUEControl();
            string max = bcCtr.GetMaxID(frmMain.__ngayMoSo.Year);
            int intMax = Convert.ToInt32(max);
            intMax++;
            return intMax.ToString("00000");
        }

        private void btnBoQua_Click(object sender, EventArgs e)
        {
            EnabledForm(false);
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            sErr = "";
            if (no != -1 && XtraMessageBox.Show("Bạn có thực sự muốn xóa?", "Thông báo", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                BUS.BAOCAOTHUEControl bcCtr = new BUS.BAOCAOTHUEControl();
                sErr = bcCtr.Delete(no);
                if (sErr == "")
                {
                    BUS.NXHOADONControl nxCtr = new BUS.NXHOADONControl();
                    nxCtr.Delete(no);
                    BUS.HACHTOANControl htCtr = new BUS.HACHTOANControl();
                    htCtr.Delete(no, ref sErr);
                    EnabledForm(false);
                    RefresForm("");
                }
                else XtraMessageBox.Show(sErr);
            }
        }

        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            frmViewBaoCaoThue frm = new frmViewBaoCaoThue();
            frm.LoaiBT = rType.EditValue.ToString();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                DTO.BAOCAOTHUEInfo inf = new DTO.BAOCAOTHUEInfo(frm.ReturnRow);
                SetData(inf);
            }
        }
        public static string GetWebPageResult(string url)
        {
            WebRequest wrGETURL = WebRequest.Create(url);
            string content = "";
            try
            {
                using (Stream objStream = wrGETURL.GetResponse().GetResponseStream())
                {
                    using (StreamReader objReader = new StreamReader(objStream, Encoding.UTF8))
                    {
                        using (WebResponse wr = wrGETURL.GetResponse())
                        {
                            using (Stream receiveStream = wr.GetResponseStream())
                            {
                                using (StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8))
                                {
                                    content = reader.ReadToEnd();
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            content = content.Replace("&nbsp;", "");
            int start = content.IndexOf("<table class=\"ta_border\">");
            if (start == -1)
                return "";
            int end = content.IndexOf("</table>", start);

            return content.Substring(start, end - start + "</table>".Length);

        }
        private void SetData(DTO.BAOCAOTHUEInfo inf)
        {
            no = inf.ID;
            sobt = inf.SOBT;
            txtDiaChi.Text = inf.DIACHI;
            txtDoanhSo.EditValue = inf.DOANHSO;
            txtKyHieuHD.Text = inf.KYHIEUHD;
            txtMaKhachHang.Text = inf.CUSINFO;
            txtMaSoThue.Text = inf.MSTHUE;
            if (inf.TENKH == "")
            {
                if (inf.MSTHUE != "")
                    txtTenDV.Text = GetMSTInfo(txtMaSoThue.Text);
            }
            else txtTenDV.Text = inf.TENKH;
            txtNgayPS.EditValue = inf.NGAYPS;
            txtNguoiMua.Text = inf.HANGHOA;
            txtSoHD.Text = inf.SOHD;
            isInHD = inf.EXP2HTKK;
            ckbCaNhan.Checked = inf.GHICHU == "Cá nhân";
            txtThueGTGT.EditValue = inf.THUEGTGT;
            txtThueSuat.EditValue = inf.THUESUAT;
            BUS.NXHOADONControl ctr = new BUS.NXHOADONControl();
            gridNXHoaDon.DataSource = ctr.GetByNo(inf.ID, ref sErr);
            SetDetailData();
            BUS.HACHTOANControl htCtr = new BUS.HACHTOANControl();
            DataTable dt = htCtr.GetByNo(inf.ID, ref sErr);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DTO.HACHTOANInfo htInf = new DTO.HACHTOANInfo(dt.Rows[i]);
                if (inf.BANRA)
                {
                    if (i == 0)
                    {
                        txtTK1.Text = htInf.TKNO;
                        txtTK2.Text = htInf.TKCO;
                        txtTKValue2.EditValue = htInf.SOTIEN;

                    }
                    else if (i == 1)
                    {
                        txtTK3.Text = htInf.TKCO;
                        txtTKValue3.EditValue = htInf.SOTIEN;
                        txtTKValue1.EditValue = ((Double)txtTKValue2.EditValue) + htInf.SOTIEN;
                    }
                }
                else
                {
                    if (i == 0)
                    {
                        txtTK1.Text = htInf.TKNO;
                        txtTK3.Text = htInf.TKCO;
                        txtTKValue1.EditValue = htInf.SOTIEN;

                    }
                    else if (i == 1)
                    {
                        txtTK2.Text = htInf.TKNO;
                        txtTKValue2.EditValue = htInf.SOTIEN;
                        txtTKValue3.EditValue = ((Double)txtTKValue1.EditValue) + htInf.SOTIEN;
                    }
                }
            }
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            if (no == -1)
            {
                XtraMessageBox.Show("Vui lòng kiểm tra lại dữ liệu đầu vào!", "Thông báo");
                return;
            }
            if (this.Parent.Parent is frmMain)
            {
                frmMain main = this.Parent.Parent as frmMain;
                Windows.Report.frmNXHoaDonCT frm = new Windows.Report.frmNXHoaDonCT(rType.EditValue.ToString() == "X-GTGT");
                frm.KyHieuHD = txtKyHieuHD.Text;
                frm.DenSoHD = frm.TuSoHD = txtSoHD.Text;
                frm.Id = no;
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    main.ShowReport(frm.DataSource, frm.Type, "Báo cáo chứng từ hóa đơn");
                }
            }
        }

        private void btnDong_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnInHD_Click(object sender, EventArgs e)
        {
            if (no == -1)
            {
                XtraMessageBox.Show("Vui lòng kiểm tra lại dữ liệu đầu vào!", "Thông báo");
                return;
            }
            bool isIn = true;
            if (this.Parent.Parent is frmMain)
            {
                frmMain main = this.Parent.Parent as frmMain;
                isIn = frmMain.IsPermis(idInHoaDon, main.CurrentPermis.PERMISSION);
                if (isInHD == true)
                {
                    if (!isIn)
                    {
                        XtraMessageBox.Show("Bạn không có quyền in lại hóa đơn!!", "Thông báo");
                        return;
                    }
                }
                Windows.Report.frmNXHoaDonCT frm = new Windows.Report.frmNXHoaDonCT(rType.EditValue.ToString() == "X-GTGT");
                frm.Id = no;
                frm.KyHieuHD = txtKyHieuHD.Text;
                frm.DenSoHD = frm.TuSoHD = txtSoHD.Text;
                DataSet ds = frm.BuildDataSourceNXHD();
                main.ShowReport(ds, "INVOICE", "Báo cáo hóa đơn");

                BUS.BAOCAOTHUEControl cbCtr = new BUS.BAOCAOTHUEControl();
                DTO.BAOCAOTHUEInfo bcInf = GetData();
                bcInf.EXP2HTKK = true;
                cbCtr.Update(bcInf);
            }
        }

        private void rType_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefresForm("");
            //if (rType.SelectedIndex == 1)
            //    colSOTIEN1.FieldName = "TIENVON";
            //else colSOTIEN1.FieldName = "SOTIEN";
            gbDetail.Text = rType.Properties.Items[rType.SelectedIndex].Description.ToUpper();
            if (rType.EditValue.ToString() == "N-GTGT")
                gbDetail.AppearanceCaption.ForeColor = Color.Red;
            else gbDetail.AppearanceCaption.ForeColor = Color.Blue;
        }

        private void NXHoaDon_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                if (txtMaSoThue.Focused || txtSoLuong.Focused)
                {
                    if (txtMaSoThue.Focused)
                    {
                        if (txtMaSoThue.Text != "")
                            txtMaSoThue.Text = "";
                        else
                        {
                            if (btnBoQua.Enabled)
                                btnBoQua_Click(null, null);
                        }
                    }
                    if (txtSoLuong.Focused)
                    {
                        if (txtMaSoThue.EditValue != null)
                            txtMaSoThue.EditValue = null;
                        else
                        {
                            gridTonHang.Focus();
                        }
                    }
                }
                else
                {
                    if (btnBoQua.Enabled)
                        btnBoQua_Click(null, null);
                }
            }
            else if (e.KeyCode == Keys.F7)
            {
                if (btnLuu.Enabled)
                    btnLuu_Click(null, null);
            }
           
        }

        private void txtMaKhachHang_TextChanged(object sender, EventArgs e)
        {
            BUS.CUSTINFOControl ctr = new BUS.CUSTINFOControl();
            DTO.CUSTINFOInfo inf = ctr.Get(txtMaKhachHang.Text, ref sErr);
            txtTenKhachHang.Text = inf.TENGD;
        }


        private void txtMaSoThue_Validating(object sender, CancelEventArgs e)
        {
            if (txtMaSoThue.Text != "")
            {
                string ten = "";
                ten = GetMSTInfo(txtMaSoThue.Text);

                if (ten == "")
                    e.Cancel = true;
                else txtTenDV.Text = ten;
                BUS.CommonControl ctr = new BUS.CommonControl();
                object a = ctr.executeScalar(String.Format("SELECT TENCOQUAN FROM MASOTHUE WHERE MST='{0}'", txtMaSoThue.Text));
                if (a != null)
                    txtDiaChi.Text = a.ToString();
            }
        }

        public static string GetMSTInfo(string strMST)
        {
            if (strMST == "")
                return "";
            string ten = "";
            BUS.CommonControl ctr = new BUS.CommonControl();
            object a = ctr.executeScalar(String.Format("SELECT TEN FROM MASOTHUE WHERE MST='{0}'", strMST));
            if (a == null || a.ToString() == "")
            {

                string value = "";
                try
                {
                    value = GetWebPageResult(string.Format(url, strMST));

                    if (value != "")
                    {
                        XmlDocument doc = new XmlDocument();
                        value = value.Replace("&nbsp;", "");

                        doc.LoadXml(value);
                        XmlElement ele = doc.DocumentElement;

                        if (ele.ChildNodes[1].ChildNodes.Count > 1)
                        {
                            string mst = ele.ChildNodes[1].ChildNodes[1].InnerText;
                            ten = ele.ChildNodes[1].ChildNodes[2].InnerText;
                            string cmt = ele.ChildNodes[1].ChildNodes[4].InnerText;
                            string tencq = ele.ChildNodes[1].ChildNodes[3].InnerText;
                            string ghichu = ele.ChildNodes[1].ChildNodes[2].InnerText;
                            ctr.executeNonQuery(string.Format("insert into MASOTHUE(MST,TEN,SOCMT,TENCOQUAN,GHICHU) VALUES(N'{0}',N'{1}',N'{2}',N'{3}',N'{4}')", mst, ten, cmt, tencq, ghichu));

                        }
                    }
                    else
                    {
                        vn.sieulienket.api.WebService api = new vn.sieulienket.api.WebService();
                        ten = api.tendoanhnghiep(strMST);
                        ctr.executeNonQuery(string.Format("insert into MASOTHUE(MST,TEN,SOCMT,TENCOQUAN,GHICHU) VALUES(N'{0}',N'{1}',N'{2}',N'{3}',N'{4}')", strMST, ten, "", "", ""));
                    }
                }
                catch { }

            }
            else ten = a.ToString();
            return ten;
        }
        double maxSoLuong = 0;
        private void btnThemChiTiet_Click(object sender, EventArgs e)
        {
            int[] currentRows = gvTonHang.GetSelectedRows();
            if (currentRows != null && currentRows.Length > 0)
            {
                DataTable dt = gridNXHoaDon.DataSource as DataTable;
                if (!dt.Columns.Contains(DTO.TONHANGInfo.Field.TENHANG.ToString()))
                {
                    dt.Columns.Add(DTO.TONHANGInfo.Field.TENHANG.ToString());
                }
                bool flag = false;
                DataRow returnRow = gvTonHang.GetDataRow(currentRows[0]);
                //foreach (DataRow row in dt.Rows)
                //{
                //    if (row.RowState != DataRowState.Deleted && returnRow[DTO.NXHOADONInfo.Field.MAHANG.ToString()].ToString() == row[DTO.TONHANGInfo.Field.MAHANG.ToString()].ToString())
                //    {
                //        flag = true;
                //        break;
                //    }
                //}
                if (flag == false)
                {
                    double soLuong = txtSoLuong.EditValue != null ? Convert.ToDouble(txtSoLuong.EditValue) : 0;
                    double donGia = txtDonGia.EditValue != null ? Convert.ToDouble(txtDonGia.EditValue) : 0;
                    BUS.TONHANGControl thCtr = new BUS.TONHANGControl();
                    DTO.TONHANGInfo tonInf = thCtr.Get(returnRow["MAHANG"].ToString(), ref sErr);// new DTO.TONHANGInfo(returnRow);
                    DTO.NXHOADONInfo hdInf = new DTO.NXHOADONInfo();
                    hdInf.DVTINH = tonInf.DVTINH;

                    hdInf.LOAICT = rType.EditValue.ToString();
                    hdInf.MAHANG = tonInf.MAHANG;
                    hdInf.SOLUONG = soLuong;
                    if (rType.SelectedIndex == 0)
                    {
                        hdInf.GIABAN = donGia;
                        hdInf.GIAVON = tonInf.GIAVON;
                        hdInf.SOTIEN = hdInf.GIABAN * hdInf.SOLUONG;
                        hdInf.TIENVON = hdInf.GIAVON * hdInf.SOLUONG;
                    }
                    else
                    {
                        hdInf.GIAVON = donGia;
                        hdInf.GIABAN = hdInf.GIAVON;
                        hdInf.SOTIEN = hdInf.GIABAN * hdInf.SOLUONG;
                        hdInf.TIENVON = hdInf.GIAVON * hdInf.SOLUONG;
                    }
                    txtSoLuong.EditValue = hdInf.SOLUONG;
                    //maxSoLuong = tonInf.SOLUONG;
                    txtDonGia.EditValue = hdInf.GIABAN;
                    txtThanhTien.EditValue = hdInf.GIAVON * tonInf.SOLUONG;
                    DataRow newRow = hdInf.ToDataRow(dt);
                    newRow[DTO.TONHANGInfo.Field.TENHANG.ToString()] = tonInf.TENHANG;
                    dt.Rows.Add(newRow);
                    //txtSoLuong.Focus();
                    gridTonHang.Focus();
                    RecalcTotal();
                    txtDonGia.EditValue = null;
                    txtSoLuong.EditValue = null;
                    txtThanhTien.EditValue = null;
                }
                else
                {
                    XtraMessageBox.Show("Mặt hàng đã tồn tại trong báo cáo!", "Thông báo");
                }
            }
        }

        private void btnXoaChiTiet_Click(object sender, EventArgs e)
        {
            int[] currentRows = gvNXHoaDon.GetSelectedRows();
            if (currentRows != null && currentRows.Length > 0)
            {
                DataRow returnRow = gvNXHoaDon.GetDataRow(currentRows[0]);
                returnRow.Delete();
                //DataTable dt = gridNXHoaDon.DataSource as DataTable;
                //dt.Rows.Remove(returnRow);
                RecalcTotal();
            }
        }

        private void RecalcTotal()
        {
            DataTable dt = gridNXHoaDon.DataSource as DataTable;
            if (dt != null)
            {
                double doanhso = 0;
                double thueGTGT = 0;
                double thueSuat = 10;
                if (txtThueSuat.EditValue != null)
                    thueSuat = Convert.ToDouble(txtThueSuat.EditValue);
                foreach (DataRow row in dt.Rows)
                {
                    if (row.RowState != DataRowState.Deleted)
                    {
                        DTO.NXHOADONInfo inf = new DTO.NXHOADONInfo(row);
                        doanhso += inf.SOTIEN;
                        giavon = inf.TIENVON;
                    }
                }
                txtDoanhSo.EditValue = doanhso;
                if (rType.EditValue.ToString() == "X-GTGT")
                {
                    txtThueGTGT.EditValue = doanhso * (thueSuat) / 100;
                    txtTKValue1.EditValue = doanhso + doanhso * (thueSuat) / 100;
                    txtTKValue2.EditValue = doanhso;
                    txtTKValue3.EditValue = doanhso * (thueSuat) / 100;
                }
                else
                {
                    txtThueGTGT.EditValue = doanhso * (thueSuat) / 100;
                    txtTKValue1.EditValue = doanhso;
                    txtTKValue2.EditValue = doanhso * (thueSuat) / 100;
                    txtTKValue3.EditValue = doanhso + doanhso * (thueSuat) / 100;
                }
            }
        }

        private void txtSoLuong_Validated(object sender, EventArgs e)
        {
            double soLuong = txtSoLuong.EditValue != null ? Convert.ToDouble(txtSoLuong.EditValue) : 0;
            double donGia = txtDonGia.EditValue != null ? Convert.ToDouble(txtDonGia.EditValue) : 0;
            txtThanhTien.EditValue = soLuong * donGia;
        }

        private void txtDonGia_Validated(object sender, EventArgs e)
        {
            double soLuong = txtSoLuong.EditValue != null ? Convert.ToDouble(txtSoLuong.EditValue) : 0;
            double donGia = txtDonGia.EditValue != null ? Convert.ToDouble(txtDonGia.EditValue) : 0;
            txtThanhTien.EditValue = soLuong * donGia;
        }

        private void gvNXHoaDon_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            SetDetailData();
        }

        private void gvNXHoaDon_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            SetDetailData();
        }

        private void SetDetailData()
        {
            int[] currentRows = gvNXHoaDon.GetSelectedRows();
            if (currentRows != null && currentRows.Length > 0)
            {
                DataRow returnRow = gvNXHoaDon.GetDataRow(currentRows[0]);
                DTO.NXHOADONInfo hdInf = new DTO.NXHOADONInfo(returnRow);
                txtSoLuong.EditValue = hdInf.SOLUONG;
                //maxSoLuong = tonInf.SOLUONG;
                txtDonGia.EditValue = hdInf.GIABAN;
                txtThanhTien.EditValue = hdInf.GIAVON * hdInf.SOLUONG;
            }
        }

        private void txtSoLuong_Validating(object sender, CancelEventArgs e)
        {
            if (rType.EditValue.ToString() == "X-GTGT")
            {
                if (gvTonHang.FocusedRowHandle > -1)
                {
                    BUS.TONHANGControl tonHCtr = new BUS.TONHANGControl();
                    DTO.TONHANGInfo inf = tonHCtr.Get(gvTonHang.GetFocusedDataRow()["MAHANG"].ToString(), ref sErr);// new DTO.TONHANGInfo(gvTonHang.GetFocusedDataRow());
                    double soluong = 0;
                    if (txtSoLuong.EditValue != null) soluong = Convert.ToDouble(txtSoLuong.EditValue);
                    DataTable dt = gridNXHoaDon.DataSource as DataTable;
                    if (dt != null)
                    {
                        foreach (DataRowView rv in dt.DefaultView)
                        {
                            if (rv[DTO.NXHOADONInfo.Field.MAHANG.ToString()].ToString() == inf.MAHANG)
                                soluong += Convert.ToDouble(rv[DTO.NXHOADONInfo.Field.SOLUONG.ToString()]);
                        }
                        if (soluong > inf.SOLUONG)
                        {
                            XtraMessageBox.Show("Số lượng xuất vượt quá số lượng tồn!");
                            e.Cancel = true;
                        }
                    }
                }
            }
        }

        private void gvTonHang_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {

        }
        bool flagUpdated = true;
        private void gvTonHang_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            if (flagUpdated)
                if (e.Row is DataRowView)
                {
                    flagUpdated = false;
                    DTO.TONHANGInfo inf = new DTO.TONHANGInfo(((DataRowView)e.Row).Row);
                    inf.SOTIEN = inf.SOLUONG * inf.GIAVON;
                    ((DataRowView)e.Row)["SOTIEN"] = inf.SOTIEN;
                    BUS.TONHANGControl ctr = new BUS.TONHANGControl();
                    ctr.Update(inf);
                    flagUpdated = true;
                }
        }

        private void txtNgayPS_Validating(object sender, CancelEventArgs e)
        {
            if (txtNgayPS.EditValue != null)
            {
                if ((DateTime)txtNgayPS.EditValue != frmMain.__ngayMoSo)
                {
                    if (XtraMessageBox.Show("Ngày giao dịch khác ngày mở sổ, Bạn có chắc muốn giao dịch trong ngày này?", "Thông báo", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    { }
                    else
                    {
                        txtNgayPS.EditValue = frmMain.__ngayMoSo;
                    }
                }
            }
            else
                e.Cancel = true;
        }

        private void txtDonGia_Enter(object sender, EventArgs e)
        {
            if (txtDonGia.EditValue == null)
            {
                if (gvTonHang.FocusedRowHandle > -1)
                {
                    DTO.TONHANGInfo inf = new DTO.TONHANGInfo(gvTonHang.GetFocusedDataRow());

                    if (rType.EditValue.ToString() == "X-GTGT")
                    {
                        txtDonGia.EditValue = inf.GIABAN;
                    }
                    else if (rType.EditValue.ToString() == "N-GTGT")
                    {
                        txtDonGia.EditValue = inf.GIAVON;
                    }
                }
            }
        }

        private void gvTonHang_Click(object sender, EventArgs e)
        {
            txtSoLuong.Focus();
            txtSoLuong.EditValue = null;
            txtDonGia.EditValue = null;
            txtThanhTien.EditValue = null;
        }

        private void txtNguoiMua_EditValueChanged(object sender, EventArgs e)
        {

        }


    }
}
